package com.aat.dxfy.buddy.test03;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.NamedElement;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatcher.Junction;
import net.bytebuddy.matcher.ElementMatchers;

public class Test03 {

	public static void main(String[] args) throws Exception {
		new Test03().test03();
	}

	// 创建子类
	public static void test01() throws Exception {
		String toString = new ByteBuddy().subclass(Object.class).name("example.Type").make()
				.load(Test03.class.getClassLoader()).getLoaded().newInstance().getClass().getName();
		System.out.println(toString);
	}

	// 创建子类
	public static void test02() throws Exception {

		String toString = new ByteBuddy().subclass(Object.class).name("example.Type")
				.method(ElementMatchers.named("toString")).intercept(FixedValue.value("Hello World!")).make()
				.load(Test03.class.getClassLoader()).getLoaded().newInstance().toString();
		System.out.println(toString);
	}

	public void test03() throws Exception {
		Foo dynamicFoo = new ByteBuddy()
				  .subclass(Foo.class)
				  .method(named("bar")).intercept(valued("One V"))
				  .method(named("foo")).intercept(valued("Two V"))
				  .method(named("foo",1)).intercept(valued("Three V"))
				  .method(named("foo",2)).intercept(valued("Four V"))
				  .make()
				  .load(getClass().getClassLoader())
				  .getLoaded()
				  .newInstance();
		System.out.println(dynamicFoo.bar());
		System.out.println(dynamicFoo.foo());
		System.out.println(dynamicFoo.foo(11));
		System.out.println(dynamicFoo.foo(11,12));
	}
	
	private Implementation valued(String string) {
		return FixedValue.value(string);
	}

	private Junction<NamedElement> named(String name) {
		return ElementMatchers.named(name);
	}
	private Junction<NamedElement> named(String methodName,int argsCount) {
		Junction<NamedElement> o=ElementMatchers.named(methodName);
		 o.and(ElementMatchers.takesArguments(argsCount));
		 return o;
	}

	public void test04() throws Exception {
		 Class<?> dynamicType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.named("toString"))
				  .intercept(MethodDelegation.to(Object.class))
				  .make()
				  .load(getClass().getClassLoader())
				  .getLoaded();
		 dynamicType.newInstance();
	}

	/**
	
	 */

}
